package top.lshaci.learning.wechat.offiaccount.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import top.lshaci.learning.wechat.offiaccount.enums.MsgType;
import top.lshaci.learning.wechat.offiaccount.model.AbstractMessage;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * MessageService
 *
 * @author lshaci
 * @since 1.0.0
 */
@Service
public class MessageService {

    /**
     * 解析请求中的 XML 数据
     *
     * @param request 微信服务器转发的请求信息
     * @return 消息内容
     * @throws IOException 读取消息时发生异常
     * @throws DocumentException 解析 XML 时发生异常
     */
    public AbstractMessage parse(HttpServletRequest request) throws IOException, DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(request.getInputStream());
        Element rootElement = document.getRootElement();
        Map<String, String> map = rootElement.elements()
                .stream()
                .collect(Collectors.toMap(e -> StrUtil.lowerFirst(e.getName()), Element::getStringValue));
        MsgType msgType = MsgType.valueOf(map.get(StrUtil.lowerFirst(MsgType.class.getSimpleName())));
        if (msgType == null) {
            return null;
        }
        return BeanUtil.mapToBean(map, msgType.getType(), true, CopyOptions.create());
    }
}
